package common

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"testing"
)

func TestGenerateToken(t *testing.T) {
	fmt.Println(GenerateToken("aaa", "bbb"))
}

// 请求结构体
type Request struct {
	Method string        `json:"method"`
	Params []interface{} `json:"params"`
}

// 响应结构体
type Response struct {
	Result interface{} `json:"result"`
	Error  string      `json:"error"`
}

// 远程方法的存根
type MathServiceStub struct {
	BaseURL string
}

// 存根方法，调用远程方法
func (m *MathServiceStub) Add(a, b int) (int, error) {
	// 构造请求
	request := Request{
		Method: "Add",
		Params: []interface{}{a, b},
	}

	// 将请求序列化为JSON
	requestData, err := json.Marshal(request)
	if err != nil {
		return 0, err
	}

	// 发送请求
	resp, err := http.Post(m.BaseURL, "application/json", bytes.NewBuffer(requestData))
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()

	// 解析响应
	var response Response
	err = json.NewDecoder(resp.Body).Decode(&response)
	if err != nil {
		return 0, err
	}

	// 检查错误
	if response.Error != "" {
		return 0, fmt.Errorf(response.Error)
	}

	// 返回结果
	result := response.Result.(float64)
	return int(result), nil
}

func TestClient(t *testing.T) {
	// 创建存根对象
	stub := &MathServiceStub{
		BaseURL: "http://localhost:8080/math", // 远程服务器的地址
	}

	// 调用远程方法
	result, err := stub.Add(12580, 20)
	if err != nil {
		fmt.Println("RPC call failed:", err)
	} else {
		fmt.Println("Result:", result) // 输出结果: 5
	}
}

// 远程方法的实现
type MathService struct{}

// 实现远程方法
func (m *MathService) Add(a, b int) int {
	return a + b
}

// 处理RPC请求的处理函数
func handleRPCRequest(w http.ResponseWriter, r *http.Request) {
	// 解析请求参数
	var request struct {
		Method string        `json:"method"`
		Params []interface{} `json:"params"`
	}

	err := json.NewDecoder(r.Body).Decode(&request)
	if err != nil {
		http.Error(w, "Invalid request", http.StatusBadRequest)
		return
	}

	// 根据请求调用对应的远程方法
	var response struct {
		Result interface{} `json:"result"`
		Error  string      `json:"error"`
	}

	switch request.Method {
	case "Add":
		// 调用Add方法
		if len(request.Params) != 2 {
			response.Error = "Invalid parameters"
		} else {
			a := request.Params[0].(float64)
			b := request.Params[1].(float64)
			result := (&MathService{}).Add(int(a), int(b))
			response.Result = result
		}
	default:
		response.Error = "Method not found"
	}

	// 将响应序列化为JSON并发送回客户端
	w.Header().Set("Content-Type", "application/json")
	err = json.NewEncoder(w).Encode(&response)
	if err != nil {
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}
}

func TestServer(t *testing.T) {
	// 注册RPC请求处理函数
	http.HandleFunc("/math", handleRPCRequest)

	// 启动HTTP服务器
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("Failed to start server:", err)
	}

}
